﻿using MyBasicLib.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace MyBasicLib.Configuration
{
   internal class ConfigStorage
    {
        string configFilePath;

        public ConfigStorage(string configFilePath)
        {
            this.configFilePath = configFilePath;
        }
        static XmlSerializer<MyBasicLibConfig> xs = new XmlSerializer<MyBasicLibConfig>();
        public MyBasicLibConfig Load()
        {
            try
            {
                if (File.Exists(configFilePath))
                {
                    var data = File.ReadAllBytes(configFilePath);
                    var tmp = xs.DeSerializer(data);
                    if (Valid(tmp))
                        return tmp;
                }
            }
            catch
            {

            }
            return null;
        }
        public void Save(MyBasicLibConfig myConfig)
        {
            try
            {
                var data = xs.Serializer(myConfig);
                File.WriteAllBytes(configFilePath, data);
            }
            catch (Exception ex)
            {
            }
        }
        public static bool Valid(MyBasicLibConfig config)
        {
            // return true;
            var tmp = config;
            if (!tmp.ObjectElementList.Any(p => p.ServiceType == typeof(MyBasicLib.Data.ORMLiteNew.IDbQueryProvider)) ||
                        !tmp.ObjectElementList.Any(p => p.ServiceType == typeof(MyBasicLib.Data.IDatabase)) ||
                        !tmp.ObjectElementList.Any(p => p.ServiceType == typeof(MyBasicLib.ILogger)))
            {
                return false;
            }
            try
            {
                //Utilities.IOC.DefaultContainer.Resolve<ILogger>();
                //Utilities.IOC.DefaultContainer.Resolve<MyBasicLib.Data.IDatabase>();
                //Utilities.IOC.DefaultContainer.Resolve<MyBasicLib.Data.ORMLiteNewNew.IDbQueryProvider>();
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}
